package com.example.shutdown_v1.service;

import com.example.shutdown_v1.dto.SensorDataPacket;
import com.example.shutdown_v1.entity.Sensor;
import com.example.shutdown_v1.entity.SensorData;
import com.example.shutdown_v1.repository.SensorDataRepository;
import com.example.shutdown_v1.repository.SensorRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 传感器数据存储服务
 * 负责将解析后的传感器数据保存到数据库
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SensorDataStorageService {
    
    private final SensorDataRepository sensorDataRepository;
    private final SensorRepository sensorRepository;
    
    /**
     * 保存传感器数据到数据库
     * @param packet 解析后的传感器数据包
     */
    @Transactional
    public void saveSensorData(SensorDataPacket packet) {
        try {
            // 1. 查询传感器信息（获取shopId）
            Sensor sensor = sensorRepository.findBySensorId(packet.getMac())
                    .orElseGet(() -> createDefaultSensor(packet.getMac()));
            
            // 2. 更新传感器最后在线时间
            sensor.setLastOnlineTime(LocalDateTime.now());
            sensorRepository.save(sensor);
            
            // 3. 创建传感器数据记录
            SensorData sensorData = new SensorData();
            sensorData.setSensorId(packet.getMac());
            sensorData.setShopId(sensor.getShopId());
            sensorData.setReceiveTime(LocalDateTime.now());
            
            // 4. 保存欧拉角（核心数据）
            if (packet.getPitch() != null) {
                sensorData.setPitch(BigDecimal.valueOf(packet.getPitch()));
                sensorData.setRoll(BigDecimal.valueOf(packet.getRoll()));
                sensorData.setYaw(BigDecimal.valueOf(packet.getYaw()));
            }
            
            // 5. 保存加速度数据
            if (packet.getAccelX() != null) {
                sensorData.setAccelX(BigDecimal.valueOf(packet.getAccelX()));
                sensorData.setAccelY(BigDecimal.valueOf(packet.getAccelY()));
                sensorData.setAccelZ(BigDecimal.valueOf(packet.getAccelZ()));
            }
            
            // 6. 保存角速度数据（新增）
            if (packet.getGyroX() != null) {
                sensorData.setGyroX(BigDecimal.valueOf(packet.getGyroX()));
                sensorData.setGyroY(BigDecimal.valueOf(packet.getGyroY()));
                sensorData.setGyroZ(BigDecimal.valueOf(packet.getGyroZ()));
            }
            
            // 7. 保存到数据库
            sensorDataRepository.save(sensorData);
            
            log.debug("[{}] 数据已保存到数据库", packet.getMac());
            
        } catch (Exception e) {
            log.error("[{}] 数据保存失败: {}", packet.getMac(), e.getMessage(), e);
            throw e;  // 抛出异常触发事务回滚
        }
    }
    
    /**
     * 创建默认传感器记录（如果数据库中不存在）
     * @param sensorId 传感器ID（MAC地址）
     * @return Sensor
     */
    private Sensor createDefaultSensor(String sensorId) {
        log.info("[{}] 首次接收数据，创建传感器记录", sensorId);
        
        Sensor sensor = new Sensor();
        sensor.setSensorId(sensorId);
        sensor.setShopId(1L);  // 默认店铺ID=1，后续可手动修改
        sensor.setInstallPosition("unknown");  // 默认未知，需要后续配置
        sensor.setStatus(1);
        
        return sensorRepository.save(sensor);
    }
    
    /**
     * 查询传感器最新的N条数据
     * @param sensorId 传感器ID
     * @param limit 限制条数
     * @return 传感器数据列表
     */
    public List<SensorData> getLatestData(String sensorId, int limit) {
        return sensorDataRepository.findLatestBySensorId(sensorId, limit);
    }
    
    /**
     * 根据传感器ID查询传感器信息
     * @param sensorId 传感器ID
     * @return Sensor
     */
    public Sensor getSensorById(String sensorId) {
        return sensorRepository.findBySensorId(sensorId).orElse(null);
    }
}

